package com.eascs.p2p.common.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StopWatch;
import com.eascs.p2p.common.dto.MessageDTO;
import com.eascs.p2p.common.dto.MessageReceiver;
import com.eascs.p2p.common.service.IMessageService;
import com.eascs.p2p.common.util.WebServiceUtil;
import com.eascs.p2p.common.vo.ModelResult;

@Service
public class MessageServiceImpl implements IMessageService{
	private final Logger logger = LoggerFactory.getLogger(MessageServiceImpl.class);
	
	@Value("${msg.webservice.url}")
	private String webserviceUrl;	//短信接口URL
	
	@Inject
	WebServiceUtil webServiceUtil;
	
	public static final String	MSG_TEMPLATE	= "<?xml version=\"1.0\" encoding=\"UTF-8\"?><sms>"
			+ "<messagecontents>%s</messagecontents><sendtype>%s</sendtype>"
			+ "<senddate>%s</senddate><creator>%s</creator>%s</sms>";

	/**
	 * 发送短信
	 * @param msg
	 * @return
	 * 2016年6月22日
	 */
	@Override
	public  ModelResult<Boolean> sendMsg(MessageDTO msg) {
		ModelResult<Boolean> result = new ModelResult<Boolean>();
		StopWatch stop = new StopWatch();
		
		List<Object> params = new ArrayList<>();
		params.add(msg.getMsgContent());
		params.add(msg.getSendType().getValue());
		params.add(msg.getSendTime());
		params.add(msg.getSenderName());
		
		List<MessageReceiver> receivers = msg.getReceivers();
		if(CollectionUtils.isEmpty(receivers)){
			throw new RuntimeException("[P2P SERVER][MessageService]消息接收人为空");
		}
		
		StringBuilder receiversStr = new StringBuilder();
		for(MessageReceiver receiver : receivers){
			receiversStr.append("<sendnos><sendno>" + receiver.getPhone() + "</sendno><sendname>"  + receiver.getName() + "</sendname></sendnos>");
		}
		params.add(receiversStr);
		
		String requestContent = String.format(MSG_TEMPLATE, params.toArray());
		
		String response = webServiceUtil.call(webserviceUrl, "sendSMS", requestContent);
		logger.info("发送短信,是否成功[{}],提示信息[{}],耗时[{}]秒", response.equals("Y") ? true : false, response, stop.elapsedTime()/1000);
		
		if(response.equals("Y")){
			result.withModel(true);
		} else{
			result.withError("发送短信失败，原因[{}]", response);
		}
		
		return result;
	}

}
